#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
from ..._util import Util, CopiedAndSymlinkedDir
from ..._game import GameBase, GameSpec, MatchContext
from ..._game_straits import GameStraitForLinux, GameStraitNeedCacheDir


class Factorio(GameBase, GameStraitForLinux):

    def __init__(self, data_dir):
        GameBase.__init__(self, data_dir)

        self._addStrait(GameStraitNeedCacheDir())

        self._binFn = os.path.join("bin", "x64", "factorio")

        self._spec = GameSpec()
        if True:
            self._spec.archs = []
            if os.path.exists(os.path.join(self._dataDir, self._binFn)):
                self._spec.archs.append("x86_64")

            self._spec.default_language = "en"
            self._spec.languages = [x.replace("-", "_") for x in os.listdir(os.path.join(self._dataDir, "data", "core", "locale"))]

            self._spec.resolutions = ["640x480", "*"]

            self._spec.can_fullscreen = True
            self._spec.can_windowed = True

            assert len(self._spec.archs) > 0
            assert self._spec.default_language in self._spec.languages

    @property
    def spec(self):
        return self._spec

    @property
    def run_items(self):
        return ["main"]

    def get_title(self, lang):
        return "Factorio"

    def _prepare(self, context):
        self._context = context
        try:
            # this game has a .lock so we can't use OverlayfsDir
            self._targetGameDirObj = CopiedAndSymlinkedDir(self._context.cache_dirpath, [self._dataDir])
            for fn in os.listdir(self._dataDir):
                if fn == "bin":
                    self._targetGameDirObj.copy(fn, recursive=True)
                else:
                    self._targetGameDirObj.symlink(fn)
        except BaseException:
            self._cleanup(on_error=True)
            raise

    @MatchContext.edit_or_run
    def get_language(self):
        return self._spec.default_language

    @MatchContext.edit_or_run
    def set_language(self, language):
        assert language == self._spec.default_language

    @MatchContext.run
    def apply_resolution(self, resolution):
        assert False

    @MatchContext.run
    def apply_fullscreen_or_windowed(self, fullscreen_or_windowed):
        assert False

    def _commit(self):
        pass

    def _getRunInfo(self, item):
        assert not self._context.edit_or_run
        assert item == Util.listGetOnlyItem(self.run_items)

        # FIXME: should be removed after we can totally eliminate X11
        envDict = {
            "SDL_VIDEODRIVER": "wayland",
        }
        return self.RunInfo(os.path.join(self._targetGameDirObj.path, self._binFn), extra_environemnt_variables=envDict)

    def _cleanup(self, on_error=False):
        if hasattr(self, "_targetGameDirObj"):
            del self._targetGameDirObj
        if hasattr(self, "_context"):
            del self._context
